﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OrderView.ViewModels;

namespace OrderView
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        List<string> openedFiles = new List<string>();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.cbbEncoding.ItemsSource = new Encoding[] { Encoding.Default, Encoding.ASCII, Encoding.UTF7, Encoding.UTF8, Encoding.Unicode, Encoding.BigEndianUnicode, Encoding.UTF32 };
            this.cbbEncoding.SelectedIndex = 0;
        }

        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var item = this.sp.Children.OfType<RadioButton>().FirstOrDefault(ri => ri.IsChecked == true);

                if (item == null)
                {
                    throw new Exception("请选择店铺名称");
                }

                Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                //ofd.Filter = "*.csv|csv file|*.*|All";
                if (ofd.ShowDialog() != true)
                {
                    return;
                }

                if (this.openedFiles.FirstOrDefault(obj => obj.Equals(ofd.FileName, StringComparison.OrdinalIgnoreCase)) != null)
                {
                    throw new Exception("文件已经打开");
                }

                List<Order> order = OrderManager.ParseFile(ofd.FileName, this.cbbEncoding.SelectedItem as Encoding, item.Content as string);
                List<Order> alreadyExistOrders = this.dgvOrders.ItemsSource as List<Order>;

                this.dgvOrders.ItemsSource = OrderManager.AlOrders(order, alreadyExistOrders);
                this.openedFiles.Add(ofd.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            this.dgvOrders.ItemsSource = null;
            this.openedFiles.Clear();
        }
    }
}
